// Copyright 2010 Google Inc. All Rights Reserved.

package com.google.zahra.webmanager;

import com.google.zahra.testmanager.TestManager;
import com.google.zahra.util.Util;

import redstone.xmlrpc.XmlRpcServlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * XML-RPC Service Servlet
 * @author arthurkok@google.com (Your Name Here)
 *
 */
public class XmlRpcService extends XmlRpcServlet {

  static final TestManager testManager = WebManager.TEST_MANAGER;
  
  @Override
  public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);
    getXmlRpcServer().addInvocationHandler("TestManager", testManager);
  }

  // If a user arrives at this URL in a browser, provide instructions
  // on how to use XML-RPC
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);
    StringBuffer bodyString = new StringBuffer();
    
    bodyString.append("<META HTTP-EQUIV='Refresh' CONTENT='1; #bottom'/>");

    bodyString.append("<h2>XML-RPC Invocation<br/></h2>");
    bodyString.append(
        "TestManager.addTestCase(byte[] python, String name, int Os, int retries)<br/>");    

    response.getWriter().print(Util.getHTML(bodyString.toString(), "Zahra - Test"));
  }

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    getXmlRpcServer().execute(request.getInputStream(), null);

    response.setContentType("text/xml");
    response.getWriter().println("<methodResponse><params><param><value><boolean>1");
    response.getWriter().println("</boolean></value></param></params></methodResponse>");
    response.getWriter().close();
  }
}